import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import type { UserInfoState } from "./interface";
import { ElMessage } from "element-plus";
// 获取全部路由组件
import { staticRoutes, asyncRoute, anyRoute } from "@/router/routes";
import { reqLogin, reqLogout, reqUserInfo } from "@/api/user";

import router from "@/router";
import cloneDeep from "lodash/cloneDeep";
import { reqFbtoken, reqBmid } from "@/api/product/trademark";
/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */

function filterRoute(asyncR: any, routerArr: any) {
  return asyncR.filter((item: any) => {
    if (routerArr.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterRoute(item.children, routerArr);
      }
      return true;
    }
  });
}
export const useUserInfoStore = defineStore("userInfo", {
  state: (): any => ({
    token: getToken() as string,
    menuRoutes: [],
    name: "",
    avatar:
      "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
    admin_user_id: "",
    newurl:null
  }),
  actions: {
    async login(username: string, password: string) {
      const result: any = await reqLogin({
        username,
        password,
      });
      // this.menuRoutes = staticRoutes;
      //本地储存token
      setToken(result.admin_token);
      //pinia 仓库储存token
      this.token = result.admin_token;
    },
    async getInfo() {
      const result: any = await reqUserInfo();
      this.name = result.username;
      // this.menuRoutes = staticRoutes;
      this.buttons = result.roles;

      const userShowAsyncRoute = filterRoute(
        cloneDeep(asyncRoute),
        result.roles
      );
      this.menuRoutes = [...staticRoutes, ...userShowAsyncRoute, anyRoute];
      [...userShowAsyncRoute, anyRoute].forEach((route: any) => {
        router.addRoute(route);
      });
    },
    async reset() {
      removeToken();
      await reqLogout();
      // 删除local中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.token = "";
      this.name = "";
      router.getRoutes().forEach((item: any) => {
        router.removeRoute(item.name);
      });
      staticRoutes.forEach((item1: any) => {
        router.addRoute(item1);
      });
    },
    saveurl(res:any){
      localStorage.setItem('url',res)
    }
  },
});
